<template>
  <div class="p-2">
    <!-- 搜索区域 -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="所属片区" prop="districtId">
              <el-select v-model="queryParams.districtId" placeholder="请选择片区" clearable>
                <el-option v-for="item in districtList" :key="item.id" :label="item.districtName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="楼宇名称" prop="housingName">
              <el-input v-model="queryParams.housingName" placeholder="请输入楼宇名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="总面积范围" prop="areaRange">
              <el-input-number v-model="queryParams.minArea" placeholder="最小面积" :min="0" :precision="2" :controls="false" style="width: 120px" />
              <span class="mx-2">-</span>
              <el-input-number v-model="queryParams.maxArea" placeholder="最大面积" :min="0" :precision="2" :controls="false" style="width: 120px" />
            </el-form-item>
            <el-form-item label="楼层范围" prop="floorRange">
              <el-input-number v-model="queryParams.minFloor" placeholder="最小楼层" :min="1" :controls="false" style="width: 120px" />
              <span class="mx-2">-</span>
              <el-input-number v-model="queryParams.maxFloor" placeholder="最大楼层" :min="1" :controls="false" style="width: 120px" />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="正常" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>

              <el-button type="warning" icon="Plus" @click="handleAdd">新增</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 列表区域 -->
    <el-card shadow="hover">
      <el-table v-loading="loading" border :data="buildingList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="所属片区" prop="districtName" width="160" align="center" />
        <el-table-column label="楼宇名称" prop="housingName" width="260" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="地址" prop="address" width="260" align="center" :show-overflow-tooltip="true" />
        <el-table-column label="楼层" prop="floor" width="160" align="center" :show-overflow-tooltip="true" />

        <el-table-column label="实景照片" align="center" width="100">
          <template #default="scope">
            <div v-if="scope.row.files && scope.row.files.length > 0" class="photo-preview">
              <el-image :src="scope.row.imageUrl" class="photo-thumb" fit="cover" style="cursor: pointer" @click="previewPhotos(scope.row)">
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </div>
            <div v-else class="no-photo" style="cursor: pointer">
              <el-icon><Picture /></el-icon>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总面积(㎡)" width="260" prop="totalArea" align="center">
          <template #default="scope">
            {{ scope.row.totalArea?.toLocaleString() }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="已出租面积(㎡)" width="160" prop="rentedArea" align="center">
          <template #default="scope">
            <span class="text-success">{{ scope.row.rentedArea?.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column label="未出租面积(㎡)" width="160" prop="availableArea" align="center">
          <template #default="scope">
            <span class="text-warning">{{ scope.row.availableArea?.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column label="入驻企业数" width="160" prop="tenantCount" align="center">
          <template #default="scope">
            {{ scope.row.tenantCount }}
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="状态" prop="status" align="center">
          <template #default="scope">
            <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column> -->
        <el-table-column label="备注" prop="remark" align="center" width="160" />
        <el-table-column label="创建时间" prop="createTime" align="center" width="160" />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button type="primary" link icon="View" @click="handleView(scope.row)">详情</el-button>
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="danger" v-if="roleSetting === 'admin'" link icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body @opened="handleDialogOpened">
      <el-tabs v-model="activeTab" type="border-card">
        <el-tab-pane label="基本信息" name="basic">
          <el-form ref="buildingFormRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="所属片区" prop="districtId">
              <el-select v-model="form.districtId" placeholder="请选择片区" style="width: 100%">
                <el-option v-for="item in districtList" :key="item.id" :label="item.districtName" :value="item.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="楼宇名称" prop="housingName">
              <el-input v-model="form.housingName" placeholder="请输入楼宇名称" />
            </el-form-item>

            <el-form-item label="总楼层" prop="floor">
              <el-input v-model="form.floor" :min="0" :max="100" placeholder="请输入楼层" @input="(v) => (form.floor = v.replace(/[^0-9]/g, ''))" />
            </el-form-item>

            <el-form-item label="总面积(㎡)" prop="totalArea">
              <el-input-number v-model="form.totalArea" placeholder="请输入总面积" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>

            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入楼宇地址" />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                  <el-radio value="0">正常</el-radio>
                  <el-radio value="1">停用</el-radio>
                </el-radio-group>
              </el-form-item> -->
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="实景照片" name="photos" :lazy="false">
          <BuildingPhotoUpload ref="photoUploadRef" :building-id="form.id" @update:photos="handlePhotosUpdate" @photo-change="handlePhotoChange" />
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 楼层面积编辑对话框 -->
    <el-dialog title="编辑楼层面积" v-model="floorAreaDialog" width="600px" append-to-body>
      <el-form label-width="100px">
        <el-table :data="floorAreaData" style="width: 100%" max-height="400">
          <el-table-column prop="floorNumber" label="楼层号" width="80" align="center">
            <template #default="scope">
              <span>第{{ scope.row.floorNumber }}层</span>
            </template>
          </el-table-column>
          <el-table-column prop="floorName" label="楼层名称" width="120">
            <template #default="scope">
              <el-input v-model="scope.row.floorName" placeholder="请输入楼层名称" />
            </template>
          </el-table-column>
          <el-table-column prop="area" label="楼层面积(㎡)">
            <template #default="scope">
              <el-input-number v-model="scope.row.area" :min="0" :precision="2" :step="0.1" style="width: 100%" placeholder="请输入面积" />
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="80" align="center">
              <template #default="scope">
                <el-button 
                  type="danger" 
                  link 
                  @click="floorAreaData.splice(scope.$index, 1)"
                  :disabled="floorAreaData.length <= 1"
                >
                  删除
                </el-button>
              </template>
            </el-table-column> -->
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveFloorAreas">保 存</el-button>
          <el-button @click="floorAreaDialog = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showPhotoDialog"
      title="图片预览"
      style="width: 90%; height: 80%; padding: 0"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <iframe :src="picUrl" frameborder="0" style="width: 100%; height: 90%"></iframe>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="Building">
import { ref, reactive, getCurrentInstance, ComponentInternalInstance, onMounted } from 'vue';
import { listDistrict, downloadImage, getBuildingList, addBuilding, updateBuilding, delBuilding } from '@/api/system/building';
import { BuildingVO, BuildingQuery, BuildingForm, DistrictVO, BuildingPhotoVO, FloorArea } from '@/api/system/building/types';
import BuildingPhotoUpload from '@/components/BuildingPhotoUpload/index.vue';
import { Picture, Edit } from '@element-plus/icons-vue';
import type { FormInstance, ElMessageBox } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));
const roleSetting = ref(localStorage.getItem('username'));
const buildingList = ref<any>([]);
const districtList = ref<DistrictVO[]>([]);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');
const open = ref(false);

const queryFormRef = ref<FormInstance>();
const buildingFormRef = ref<FormInstance>();

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  housingName: undefined,
  buildingCode: undefined,
  districtId: undefined,
  minArea: undefined,
  maxArea: undefined,
  minFloors: undefined,
  maxFloors: undefined,
  status: undefined
});

const form = ref<any>({ housingName: '', districtId: '', totalArea: '', floor: '' });
const activeTab = ref('basic');
const floorAreaDialog = ref(false);
const floorAreaData = ref<FloorArea[]>([]);

const picUrl = ref('');

const rules = ref({
  housingName: [{ required: true, message: '楼宇名称不能为空', trigger: 'blur' }],
  buildingCode: [{ required: true, message: '楼宇代码不能为空', trigger: 'blur' }],
  floor: [{ required: true, message: '楼层不能为空', trigger: 'blur' }],
  districtId: [{ required: true, message: '请选择所属片区', trigger: 'change' }],
  totalArea: [{ required: true, message: '总面积不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '总楼层不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
});

/** 查询楼宇列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await getBuildingList(queryParams.value);
    buildingList.value = res.rows;

    buildingList.value.forEach(async (item: any) => {
      if (item.files?.length) {
        const url = await getPhotoUrl(item);
        item.imageUrl = url;
      }
    });

    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 查询楼宇列表 */
const getAreaList = async () => {
  //queryParams.value
  const res = await listDistrict({ pageNum: 1, pageSize: 10 });
  districtList.value = res.rows;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    buildingName: undefined,
    buildingCode: undefined,
    districtId: undefined,
    minArea: undefined,
    maxArea: undefined,
    minFloors: undefined,
    maxFloors: undefined,
    status: undefined
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: BuildingVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  title.value = '新增楼宇';
  open.value = true;
};

/** 修改按钮操作 */
const handleUpdate = (row: any) => {
  reset();
  form.value = { ...row };
  form.value.photos = form.value.files;
  title.value = '修改楼宇';
  open.value = true;
};

const handleDialogOpened = () => {
  photoUploadRef.value.initData(form.value);
  // activeTab.value = 'photos';
  // Watch for component ref to become available
  // const unwatch = watch(
  //   () => photoUploadRef.value,
  //   (instance) => {
  //     if (instance) {
  //       instance.initData(form.value);
  //       unwatch(); // Stop watching after successful initialization
  //     }
  //   },
  //   { immediate: true }
  // );
};

/** 详情按钮操作 */
const handleView = (row: BuildingVO) => {
  // 跳转到房间列表页面并携带楼宇ID参数
  const router = proxy?.$router;
  if (router) {
    router.push({
      path: '/task/roomList',
      query: {
        buildingId: row.id,
        buildingName: row.buildingName
      }
    });
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: BuildingVO) => {
  const buildingIds = row?.id || ids.value;
  await proxy?.$modal.confirm(`是否确认删除选中的数据？`);
  await delBuilding(buildingIds);
  proxy?.$modal.msgSuccess('删除成功');
  getList();
};

/** 提交按钮 */
const submitForm = () => {
  buildingFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.id) {
        console.log('===form.value', form.value);
        // 处理照片上传逻辑
        if (form.value.photos?.length) {
          form.value.photos.forEach((item: any) => {
            if (item.remark == null) {
              item.remark = '';
            }
          });
        }
        const params = {
          id: form.value.id,
          // buildingName: form.value.buildingName || '',
          // buildingCode: form.value.buildingCode || '',
          floor: Number(form.value.floor) || 0,
          districtId: form.value.districtId || '',
          totalArea: Number(form.value.totalArea) || 0,
          totalFloors: Number(form.value.totalFloors) || 0,
          address: form.value.address || '',
          status: form.value.status || '',
          remark: form.value.remark || '',
          housingName: form.value.housingName || '',
          files: form.value.photos || []
          // floorAreas: form.value.floorAreas || []
        };

        await updateBuilding(params);
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        const params = {
          // buildingName: form.value.buildingName || '',
          // buildingCode: form.value.buildingCode || '',
          districtId: form.value.districtId || '',
          totalArea: Number(form.value.totalArea) || 0,
          totalFloors: Number(form.value.totalFloors) || 0,
          floor: Number(form.value.floor) || 0,
          address: form.value.address || '',
          status: form.value.status || '',
          housingName: form.value.housingName || '',
          remark: form.value.remark || '',
          files: form.value.photos || []
          // floorAreas: form.value.floorAreas || []
        };
        await addBuilding(params);
        proxy?.$modal.msgSuccess('新增成功');
      }
      open.value = false;
      getList();
    }
  });
};

const photoUploadRef = ref(null);
// 调用子组件方法传值

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 编辑楼层面积 */
const editFloorAreas = () => {
  if (!form.value.totalFloors || form.value.totalFloors <= 0) {
    proxy?.$modal.msgWarning('请先设置总楼层数');
    return;
  }

  // 初始化楼层面积数据
  const totalFloors = form.value.totalFloors;
  floorAreaData.value = [];

  // 如果已有楼层面积数据，使用现有数据
  if (form.value.floorAreas && form.value.floorAreas.length > 0) {
    floorAreaData.value = [...form.value.floorAreas];
  }

  // 确保有totalFloors个楼层的数据
  for (let i = 1; i <= totalFloors; i++) {
    const existingFloor = floorAreaData.value.find((f) => f.floorNumber === i);
    if (!existingFloor) {
      floorAreaData.value.push({
        floorNumber: i,
        area: 0,
        floorName: `第${i}层`
      });
    }
  }

  // 按楼层号排序
  floorAreaData.value.sort((a, b) => a.floorNumber - b.floorNumber);

  // 只保留totalFloors个楼层的数据
  floorAreaData.value = floorAreaData.value.slice(0, totalFloors);

  floorAreaDialog.value = true;
};

/** 保存楼层面积 */
const saveFloorAreas = () => {
  form.value.floorAreas = [...floorAreaData.value];
  floorAreaDialog.value = false;
  proxy?.$modal.msgSuccess('楼层面积保存成功');
};

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    buildingName: '',
    buildingCode: '',
    districtId: '',
    totalArea: 0,
    totalFloors: 1,
    address: '',
    status: '0',
    remark: '',
    photos: [],
    floorAreas: [],
    files: []
  };
  activeTab.value = 'basic';
  buildingFormRef.value?.resetFields();
};

/** 处理照片更新 */
const handlePhotosUpdate = (photos: BuildingPhotoVO[]) => {
  form.value.photos = photos;
};

/** 处理照片变化 */
const handlePhotoChange = () => {
  // 照片变化时的处理逻辑
};

/** 获取照片URL */
const getPhotoUrl = async (data: any) => {
  if (data.files[0].id) {
    try {
      // 发送POST请求获取图片流
      const response = await downloadImage(data.files[0].id);
      console.log('response', response);
      // 验证响应是否为blob格式
      if (response instanceof Blob) {
        // 将blob转换为Data URL
        return URL.createObjectURL(response);

        data.files[0].imageUrl = data.imageUrl;
        return data.imageUrl;
      } else {
        console.error('响应不是blob格式:', response);
      }
    } catch (error) {
      console.error('获取图片失败:', error);
    }
  }
};

/** 获取照片列表用于预览 */
const getPhotoList = (photos: BuildingPhotoVO[]) => {
  return photos.map((photo) => getPhotoUrl(photo));
};

// 定义图片类型接口
interface ImageItem {
  url: string;
  thumbnailUrl: string;
  description: string;
}

// 图片预览弹窗状态
const showPhotoDialog = ref(false);
// 弹窗图片数据 - 添加类型定义
const dialogImages = ref<ImageItem[]>([]);
// 当前图片索引
const currentIndex = ref(0);

// 计算属性：当前图片
const currentImage = computed(() => {
  return dialogImages.value[currentIndex.value];
});

// 上一张图片
const prevImage = () => {
  if (currentIndex.value > 0) {
    currentIndex.value--;
  } else {
    currentIndex.value = dialogImages.value.length - 1;
  }
};

// 下一张图片
const nextImage = () => {
  if (currentIndex.value < dialogImages.value.length - 1) {
    currentIndex.value++;
  } else {
    currentIndex.value = 0;
  }
};

/** 预览照片 */
const previewPhotos = (photos: any) => {
  showPhotoDialog.value = true;
  picUrl.value = '/roomListPic?id=' + photos.id + '&t=' + new Date().getTime();
};

onMounted(() => {
  getList();
  getAreaList();
});
</script>

<style scoped>
.text-success {
  color: #67c23a;
}
.text-warning {
  color: #e6a23c;
}

.photo-preview {
  position: relative;
  display: inline-block;
}

.photo-thumb {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #e4e7ed;
}

.photo-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  width: 18px;
  height: 18px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-photo {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}

/* 图片预览弹窗样式 */
.image-gallery {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 20px;
}

.main-image-container {
  position: relative;
  width: 100%;
  height: calc(100vh - 150px);
  display: flex;
  align-items: center;
  justify-content: center;
}

.main-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.image-description {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px 10px;
  border-radius: 5px;
}

.arrow {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 15px 10px;
  cursor: pointer;
  font-size: 24px;
  border-radius: 5px;
  z-index: 1;
}

.arrow.left {
  left: 20px;
}

.arrow.right {
  right: 20px;
}

.thumbnail-container {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
  padding: 20px;
  max-height: 120px;
  overflow-x: auto;
}

.thumbnail {
  width: 100px;
  height: 100px;
  border: 2px solid transparent;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s ease;
  flex-shrink: 0;
}

.thumbnail.active {
  border-color: #409eff;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.close-btn {
  position: absolute;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  font-size: 24px;
  cursor: pointer;
  z-index: 100;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}
</style>
